package com.mazaiting.manager.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.mazaiting.web.utils.UserUtil;
import com.mazaiting.manager.config.mp.handler.DeptPermissionHandler;
import com.mazaiting.mybatisplus.config.MyBatisAutoConfiguration;
import com.mazaiting.mybatisplus.service.IUserMetaObjectService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * Mybatis 配置
 *
 * @author mazaiting
 * @create_time 2022/9/20 21:28
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@AutoConfigureBefore(MyBatisAutoConfiguration.class)
public class MybatisConfig {

    private final MybatisPlusInterceptor mybatisPlusInterceptor;

    /**
     * 默认提供源数据服务
     * 如果是 sys_access_log 表操作会进入异常, 因为此时还未登录成功
     * @return 源数据服务
     */
    @Bean
    @ConditionalOnMissingBean
    public IUserMetaObjectService userMetaObjectService() {
        return () -> {
            try {
                return UserUtil.getUserId();
            } catch (Exception e) {
                log.error("获取用户 ID 异常: " + e.getMessage());
                return -1L;
            }
        };
    }

    /**
     * 设置拦截器, 对拦截器进行扩展
     */
    @PostConstruct
    public void setInterceptor() {
        List<InnerInterceptor> interceptors = new ArrayList<>();
        interceptors.add(new DataPermissionInterceptor(new DeptPermissionHandler()));
        interceptors.addAll(mybatisPlusInterceptor.getInterceptors());
        mybatisPlusInterceptor.setInterceptors(interceptors);
        log.info("修改 Mybatis 拦截器顺序成功");
    }
}
